//用户vuex 数据模块

import { api_users_checkLogin, api_users_info } from "@/apis/user";
const state = {
	// 刷新后以本地存储的数据赋值给vuex
	token: localStorage.getItem("t_k"),
	role: localStorage.getItem("role"),
	userInfo: {},
};

const getters = {};
//同步方法
const mutations = {
	SET_TOKEN(state, data) {
		state.token = data;
		// 因为数据存vuex，刷新后数据会丢失，所以再存一份本地
		localStorage.setItem("t_k", data);
	},
	SET_ROLE(state, data) {
		state.role = data;
		localStorage.setItem("role", data);
	},
	SET_USERINFO(state, data) {
		state.userInfo = data;
	},
	//  清空state中的数据
	CLEAR(state) {
		(state.token = ""),
			(state.role = ""),
			(state.userInfo = {}),
			localStorage.clear();
	},
};
// 异步方法
const actions = {
	// 登录
	$_UserLogin({ commit }, data) {
		return new Promise(async (resolve) => {
			const res = await api_users_checkLogin(data);
			let { code, msg, token, role } = res.data;
			// console.log(res.data);
			if (code == 0) {
				commit("SET_TOKEN", "Bearer " + token);
				commit("SET_ROLE", role);
				resolve();
			}
		});
	},
	// 获取个人信息
	$_UserInfo({ commit }) {
		return new Promise(async (resolve, reject) => {
			try {
				const res = await api_users_info();
				//   console.log(res);
				commit("SET_USERINFO", res.data);
				resolve();
			} catch (error) {
				reject(error);
			}
		});
	},
	//   退出登录清空本地存储，vuex中token和role数据
	$_Clear({ commit }) {
		return new Promise((resolve) => {
			commit("CLEAR");
			resolve();
		});
	},
};

export default {
	//命名空间
	namespaced: true,
	state,
	getters,
	mutations,
	actions,
};
